using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using JlPay.Sdk.Core;
using JlPay.Sdk.Models;

namespace JlPay.Sdk.Models.Openmerch.Bill
{
    /// <summary>
    /// 结算账单查询响应
    /// @author liaochangyi
    /// @since 2025-01-25
    /// </summary>
    public class SettleBillQueryResponse : StandardResponse
    {
        /// <summary>
        /// 错误信息
        /// </summary>
        [JsonPropertyName("err_msg")]
        public string? ErrMsg { get; set; }

        /// <summary>
        /// 商户号
        /// </summary>
        [JsonPropertyName("merch_no")]
        public string? MerchNo { get; set; }

        /// <summary>
        /// 开始营业日期，yyyy-MM-dd
        /// </summary>
        [JsonPropertyName("start_busi_date")]
        public string? StartBusiDate { get; set; }

        /// <summary>
        /// 结束营业日期
        /// </summary>
        [JsonPropertyName("end_busi_date")]
        public string? EndBusiDate { get; set; }

        /// <summary>
        /// 开始结算日期，yyyy-MM-dd
        /// </summary>
        [JsonPropertyName("start_settle_date")]
        public string? StartSettleDate { get; set; }

        /// <summary>
        /// 结束结算日期
        /// </summary>
        [JsonPropertyName("end_settle_date")]
        public string? EndSettleDate { get; set; }

        /// <summary>
        /// 付款金额
        /// </summary>
        [JsonPropertyName("pay_amt")]
        public string? PayAmt { get; set; }

        /// <summary>
        /// 交易笔数
        /// </summary>
        [JsonPropertyName("trans_count")]
        public string? TransCount { get; set; }

        /// <summary>
        /// 账单明细列表
        /// </summary>
        [JsonPropertyName("bill_detail_list")]
        public List<BillDetail>? BillDetailList { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public SettleBillQueryResponse()
        {
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="responseData">响应数据</param>
        public SettleBillQueryResponse(Dictionary<string, object> responseData)
        {
            // 处理基础响应字段
            if (responseData.TryGetValue("ret_code", out var retCode))
            {
                RetCode = retCode?.ToString();
            }
            if (responseData.TryGetValue("ret_msg", out var retMsg))
            {
                RetMsg = retMsg?.ToString();
            }

            // 处理业务字段
            ErrMsg = responseData.TryGetValue("err_msg", out var errMsg) ? errMsg?.ToString() : null;
            MerchNo = responseData.TryGetValue("merch_no", out var merchNo) ? merchNo?.ToString() : null;
            StartBusiDate = responseData.TryGetValue("start_busi_date", out var startBusiDate) ? startBusiDate?.ToString() : null;
            EndBusiDate = responseData.TryGetValue("end_busi_date", out var endBusiDate) ? endBusiDate?.ToString() : null;
            StartSettleDate = responseData.TryGetValue("start_settle_date", out var startSettleDate) ? startSettleDate?.ToString() : null;
            EndSettleDate = responseData.TryGetValue("end_settle_date", out var endSettleDate) ? endSettleDate?.ToString() : null;
            PayAmt = responseData.TryGetValue("pay_amt", out var payAmt) ? payAmt?.ToString() : null;
            TransCount = responseData.TryGetValue("trans_count", out var transCount) ? transCount?.ToString() : null;

            // 处理账单明细列表
            if (responseData.TryGetValue("bill_detail_list", out var billDetailListData) && billDetailListData != null)
            {
                if (billDetailListData is List<object> detailList)
                {
                    BillDetailList = new List<BillDetail>();
                    foreach (var detail in detailList)
                    {
                        if (detail is Dictionary<string, object> detailDict)
                        {
                            BillDetailList.Add(new BillDetail(detailDict));
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 重写HandleResponse方法，确保响应报文格式完全符合预期
        /// </summary>
        /// <param name="operationName">操作名称</param>
        /// <param name="config">配置对象</param>
        public new void HandleResponse(string operationName, Config? config = null)
        {
            if (IsSuccess())
            {
                Console.WriteLine($"{operationName}成功！");
                
                // 手动构建响应JSON，确保字段名称和结构完全符合预期
                var responseData = new Dictionary<string, object>
                {
                    ["ret_code"] = RetCode ?? "",
                    ["ret_msg"] = RetMsg ?? "",
                    ["err_msg"] = ErrMsg ?? "",
                    ["merch_no"] = MerchNo ?? "",
                    ["start_busi_date"] = StartBusiDate ?? "",
                    ["end_busi_date"] = EndBusiDate ?? "",
                    ["start_settle_date"] = StartSettleDate ?? "",
                    ["end_settle_date"] = EndSettleDate ?? "",
                    ["pay_amt"] = PayAmt ?? "",
                    ["trans_count"] = TransCount ?? ""
                };

                // 转换账单明细列表
                if (BillDetailList != null)
                {
                    var detailList = new List<Dictionary<string, object?>>();
                    foreach (var detail in BillDetailList)
                    {
                        detailList.Add(detail.ToDictionary());
                    }
                    responseData["bill_detail_list"] = detailList;
                }
                else
                {
                    responseData["bill_detail_list"] = new List<Dictionary<string, object?>>();
                }
                
                Console.WriteLine("响应报文：" + JsonSerializer.Serialize(responseData, new JsonSerializerOptions 
                { 
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                }));
            }
            else
            {
                Console.WriteLine($"{operationName}失败: {RetCode} - {RetMsg}");
            }
        }
    }
} 